import numpy as np
import csv
import random
from datetime import datetime
from time import strftime
from dbfpy import dbf

'''
read dbf file
'''

def getCurTime():
    """
    get current time
    Return value of the date string format(%Y-%m-%d %H:%M:%S)
    """
    format='%Y-%m-%d %H:%M:%S'
    sdate = None
    cdate = datetime.now()
    try:
        sdate = cdate.strftime(format)
    except:
        raise ValueError
    return sdate

def build_data_list(inputCSV):
    sKey = []
    fn = inputCSV
    ra = csv.DictReader(file(fn), dialect="excel")
    i = 0
    for record in ra:
        #print record[ra.fieldnames[0]], type(record[ra.fieldnames[-1]])
        sKey.append(ra.fieldnames[3])
        sKey.append(ra.fieldnames[-2])
        sKey.append(ra.fieldnames[-1])
        print i
        i += 1
    sKey = np.array(sKey)
    sKey.shape=(-1,3)
    return sKey


def build_data_dbf(inputDBF):
    sKey = []
    fn = inputDBF
    ra = dbf.Dbf(fn)
    for record in ra:
        #temp = float(record[db.fieldNames[2]])
        sKey.append(record[ra.fieldNames[3]])
        sKey.append(record[ra.fieldNames[-2]])
        sKey.append(record[ra.fieldNames[-1]])
    sKey = np.array(sKey)
    sKey.shape = (-1, 3)
    return sKey


#--------------------------------------------------------------------------
#MAIN
if __name__ == "__main__":
    print "begin at " + getCurTime()
    filePath = 'C:/_DATA/US/Counties/'
    inputDBF = filePath + 'tl_2010_us_county10.dbf'
    data = build_data_dbf(inputDBF)


    fileLoc = 'C:/_DATA/migration89_08/COUNTY Migration/SaTScan/county.geo'
    np.savetxt(fileLoc, data, delimiter=' ', fmt = '%s')

    print "end at " + getCurTime()
    print "========================================================================"  
    
            